package com.czl.lunt.service.impl;

import com.czl.lunt.Exception.ApplicationException;
import com.czl.lunt.common.Result;
import com.czl.lunt.common.ResultCode;
import com.czl.lunt.dao.ArticleReplyMapper;
import com.czl.lunt.model.ArticleReply;
import com.czl.lunt.service.ArticleReplyService;
import com.czl.lunt.service.ArticleService;
import com.czl.lunt.utils.StringUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements ArticleReplyService {
    @Autowired
    private ArticleReplyMapper articleReplyMapper;

    @Autowired
    private ArticleService articleService;

    @Override
    public void create(ArticleReply articleReply) {

        if (articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtils.isEmpty(articleReply.getContent())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if(row != 1){
            log.info("帖子插入失败");
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        articleService.addOneReplyById(articleReply.getArticleId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(@NonNull Long articleId) {
        if(articleId < 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleReplyMapper.selectByArticleId(articleId);
    }
}
